package com.xindaoapp.happypet.ui;

import java.util.List;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v4.widget.DrawerLayout;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.application.HappyPetApplication;
import com.xindaoapp.happypet.bean.RecommendCicleData;
import com.xindaoapp.happypet.bean.RecommendCicleData.RecommendCicle;
import com.xindaoapp.happypet.utils.CommonParameter;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.IRequest;
import com.xindaoapp.happypet.utils.LoginManager;
import com.xindaoapp.happypet.view.FixGridLayout;

/**
 * 主页_最新
 * 
 * @author Stone
 */
public class MainFragment_New extends BaseFragment implements OnClickListener {

    public MainFragment_New() {
        super();
    }

    private TextView tv_title;
    private ImageView iv_left, iv_right;
    /** 切换tab */
    private ViewPager viewPager;
    private PopupWindow mPopupWindow1, mPopupWindow2;
    private List<RecommendCicleData.RecommendCicle> mCicles1, mCicles2;
    private FixGridLayout layout_changyong, layout_huodong;
    private RelativeLayout lay_scroll;
    private DrawerLayout mDrawerLayout;
    private ImageView iv_closepop, iv_refresh;
    private HasNewReceiver mHasNewReceiver;
    private Animation operatingAnim;

    /**
     * tab初始化
     */
    private View tab_zuixin, tab_haoyou, tab_meitu, lay_left, lay_right;
    private View iv_point2, iv_point3;
    private TextView tv_zuixin, tv_haoyou, tv_meitu, tv_line1, tv_line2, tv_line3;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return mView = inflater.inflate(R.layout.fragment_main_new, container, false);
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    protected void initViews() {
        super.initViews();

        mHasNewReceiver = new HasNewReceiver();
        mContext.registerReceiver(mHasNewReceiver, new IntentFilter(Constants.ACTION_HASNEW));

        mDrawerLayout = (DrawerLayout) getActivity().findViewById(R.id.drawer_layout);
        mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);

        Fragment[] fragments =
                new Fragment[] {ZuiXinFragment.newInstance(true),
                        ZuiXinFragment.newInstance(false), BeautifulFragment.newInstance()};


        String[] hasRights = new String[] {"1", "1", "1"};



        iv_left = (ImageView) mView.findViewById(R.id.iv_left);
        iv_right = (ImageView) mView.findViewById(R.id.iv_right);

        lay_left = mView.findViewById(R.id.lay_left);
        lay_right = mView.findViewById(R.id.lay_right);

        iv_point2 = mView.findViewById(R.id.iv_point2);
        iv_point3 = mView.findViewById(R.id.iv_point3);
        tv_line1 = (TextView) mView.findViewById(R.id.tv_line1);
        tv_line2 = (TextView) mView.findViewById(R.id.tv_line2);
        tv_line3 = (TextView) mView.findViewById(R.id.tv_line3);
        tv_zuixin = (TextView) mView.findViewById(R.id.tv_zuixin);
        tv_haoyou = (TextView) mView.findViewById(R.id.tv_haoyou);
        tv_meitu = (TextView) mView.findViewById(R.id.tv_meitu);
        tab_zuixin = mView.findViewById(R.id.tab_zuixin);
        tab_haoyou = mView.findViewById(R.id.tab_haoyou);
        tab_meitu = mView.findViewById(R.id.tab_meitu);

        viewPager = (ViewPager) mView.findViewById(R.id.viewpager);

        initPop2();

        MainViewPagerAdapter adapter =
                new MainViewPagerAdapter(getChildFragmentManager(), fragments, hasRights);

        viewPager.setAdapter(adapter);
        viewPager.setOffscreenPageLimit(3);
        viewPager.setOnPageChangeListener(adapter);

        new LoginManager(getActivity()).autoLogin();
    }


    private void changeTab(int i) {
        iniTabSelectedSetting();
        switch (i) {
            case 0:
                tv_zuixin.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
                tab_zuixin.setSelected(true);
                tv_line1.setVisibility(View.VISIBLE);
                goAnim(tv_line1);
                // goAnim(tv_zuixin);
                break;
            case 1:
                if (iv_point2.getVisibility() == View.VISIBLE) {
                    iv_point2.setVisibility(View.GONE);
                }
                tv_haoyou.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
                tab_haoyou.setSelected(true);
                tv_line2.setVisibility(View.VISIBLE);
                goAnim(tv_line2);
                // goAnim(tv_haoyou);
                break;
            case 2:
                if (iv_point3.getVisibility() == View.VISIBLE) {
                    iv_point3.setVisibility(View.GONE);
                }
                tv_meitu.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
                tab_meitu.setSelected(true);
                tv_line3.setVisibility(View.VISIBLE);
                goAnim(tv_line3);
                // goAnim(tv_meitu);

                break;
            default:
                break;
        }

    }


    private void goAnim(TextView tv_line) {
        final AlphaAnimation alphaAnimation = new AlphaAnimation(0.3f, 1.0f);
        alphaAnimation.setDuration(200);
        // alphaAnimation.setFillAfter(true);// 动画执行完的状态显示
        // alphaAnimation.setAnimationListener(new AnimationListener() {
        //
        // @Override
        // public void onAnimationStart(Animation arg0) {
        // // TODO Auto-generated method stub
        // }
        //
        // @Override
        // public void onAnimationRepeat(Animation arg0) {
        // // TODO Auto-generated method stub
        // }
        //
        // @Override
        // public void onAnimationEnd(Animation arg0) {
        // // TODO Auto-generated method stub
        // alphaAnimation.cancel();
        // }
        // });
        tv_line.startAnimation(alphaAnimation);

    }

    private void iniTabSelectedSetting() {
        tv_zuixin.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
        tv_haoyou.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
        tv_meitu.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
        tab_zuixin.setSelected(false);
        tab_haoyou.setSelected(false);
        tab_meitu.setSelected(false);
        tv_line1.setVisibility(View.GONE);
        tv_line2.setVisibility(View.GONE);
        tv_line3.setVisibility(View.GONE);
    }

    @Override
    protected void initEvents() {
        super.initEvents();
        lay_left.setOnClickListener(this);
        lay_right.setOnClickListener(this);
        tab_zuixin.setOnClickListener(this);
        tab_haoyou.setOnClickListener(this);
        tab_meitu.setOnClickListener(this);
    }

    @Override
    protected void loadDatas() {
        super.loadDatas();
        getData();
    }

    @Override
    public void onDestroyView() {
        // TODO Auto-generated method stub
        super.onDestroyView();
        mContext.unregisterReceiver(mHasNewReceiver);
    }

    private void getData() {
        // TODO Auto-generated method stub

        HappyPetApplication.get().getMoccaApi()
                .getRecommendCicleData(new IRequest<RecommendCicleData>() {

                    @Override
                    public void request(RecommendCicleData t) {



                        if (t == null) {

                        } else {

                            if (operatingAnim != null) {
                                iv_refresh.clearAnimation();
                            }

                            if (!(t.array1.size() == 0)) {
                                // 适配上
                                mCicles1 = t.array1;
                                // gridView.setAdapter(new QuanziAdapter());
                                bindData(true);
                            }
                            if (!(t.array2.size() == 0)) {
                                // 适配上
                                mCicles2 = t.array2;
                                // gridView.setAdapter(new QuanziAdapter());
                                bindData(false);
                            }
                        }
                    }

                    private void bindData(final boolean isNormal) {

                        if (isNormal) {
                            layout_changyong.removeAllViews();
                        } else {
                            layout_huodong.removeAllViews();
                        }

                        final List<RecommendCicle> cicles;
                        cicles = isNormal ? mCicles1 : mCicles2;
                        for (int i = 0; i < cicles.size(); i++) {
                            final int j = i;
                            View view =
                                    LayoutInflater.from(mContext).inflate(R.layout.item_quanzi,
                                            null);
                            TextView tView = (TextView) view.findViewById(R.id.tv_quanzi);
                            tView.setText(cicles.get(i).tagname);
                            tView.setOnClickListener(new OnClickListener() {

                                @Override
                                public void onClick(View arg0) {
                                    // TODO 跳转到标签帖子列表
                                    mPopupWindow2.dismiss();

                                    Intent intent = new Intent(mContext, MyTagListActivity.class);
                                    intent.putExtra(Constants.KEY_GROUP_NAME, cicles.get(j).tagname);
                                    intent.putExtra(Constants.KEY_TAGID, cicles.get(j).tagid);
                                    startActivity(intent);

                                }
                            });
                            if (isNormal) {
                                layout_changyong.addView(view);
                            } else {
                                layout_huodong.addView(view);
                            }
                        }


                    }
                });


    }

    @Override
    public void onClick(View view) {
        // TODO Auto-generated method stub
        switch (view.getId()) {
            case R.id.lay_left:
                // 预留
                mDrawerLayout.openDrawer(Gravity.LEFT);
                break;
            case R.id.lay_right:
                mPopupWindow2.showAtLocation(mView, Gravity.CENTER, 0, 0);
                break;
            case R.id.tab_zuixin:
                viewPager.setCurrentItem(0);
                break;
            case R.id.tab_haoyou:
                viewPager.setCurrentItem(1);
                break;
            case R.id.tab_meitu:
                viewPager.setCurrentItem(2);
                break;


            default:
                break;
        }

    }

    private void initPop2() {

        // TODO Auto-generated method stub
        LayoutInflater mLayoutInflater = LayoutInflater.from(mContext);
        /* 设置显示menu布局 view子VIEW */
        View sub_view = mLayoutInflater.inflate(R.layout.item_pop2, null);

        iv_closepop = (ImageView) sub_view.findViewById(R.id.iv_closepop);
        layout_changyong = (FixGridLayout) sub_view.findViewById(R.id.lay_changyong);
        layout_huodong = (FixGridLayout) sub_view.findViewById(R.id.lay_huodong);
        lay_scroll = (RelativeLayout) sub_view.findViewById(R.id.lay_scroll);
        iv_refresh = (ImageView) sub_view.findViewById(R.id.iv_refresh);

        RelativeLayout.LayoutParams layoutParams =
                (android.widget.RelativeLayout.LayoutParams) lay_scroll.getLayoutParams();
        layoutParams.width = LayoutParams.MATCH_PARENT;
        layoutParams.height = CommonParameter.sScreenHeight / 2;
        lay_scroll.setLayoutParams(layoutParams);

        layout_changyong.removeAllViewsInLayout();
        layout_huodong.removeAllViewsInLayout();

        /* 第一个参数弹出显示view 后两个是窗口大小 */
        mPopupWindow2 =
                new PopupWindow(sub_view, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        /* 设置背景显示 */
        mPopupWindow2.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        /* 设置系统动画 */
        // mPopupWindow2.setAnimationStyle(R.style.Pop_Custom);
        mPopupWindow2.setAnimationStyle(android.R.style.Animation_Dialog);
        /* 设置点击menu以外其他地方以及返回键退出 */
        mPopupWindow2.setFocusable(true);
        // 设置允许在外点击消失
        mPopupWindow2.setOutsideTouchable(true);
        sub_view.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                mPopupWindow2.dismiss();
            }
        });

        iv_closepop.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                mPopupWindow2.dismiss();
            }
        });

        operatingAnim = AnimationUtils.loadAnimation(getActivity(), R.anim.rotateanimation);
        LinearInterpolator lin = new LinearInterpolator();
        operatingAnim.setInterpolator(lin);


        // animation =
        // new RotateAnimation(0f, 360f, Animation.RELATIVE_TO_SELF, 0.5f,
        // Animation.RELATIVE_TO_SELF, 0.5f);
        // animation.setFillAfter(false);
        // animation.setRepeatCount(0);// 设置重复次数
        // animation.setDuration(200);
        // LinearInterpolator lin = new LinearInterpolator();
        // animation.setInterpolator(lin);
        // iv_refresh.setAnimation(animation);
        iv_refresh.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (operatingAnim != null) {
                    iv_refresh.startAnimation(operatingAnim);
                }
                getData();
            }
        });

        mPopupWindow2.update();


    }

    @SuppressLint("NewApi")
    /**
     * tab切换适配器
     * 
     * @author Stone
     * 
     */
    public class MainViewPagerAdapter extends FragmentPagerAdapter implements OnPageChangeListener {
        Fragment[] fragments;

        public MainViewPagerAdapter(FragmentManager fm, Fragment[] fragments, String[] hasRights) {
            super(fm);
            this.fragments = fragments;
            changeTab(0);
        }

        @Override
        public Fragment getItem(int arg0) {
            return fragments[arg0];
        }

        @Override
        public int getCount() {
            return fragments.length;
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {}

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {}

        @Override
        public void onPageSelected(int position) {
            changeTab(position);
        }


    }


    class HasNewReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            iv_point2
                    .setVisibility(Integer.parseInt(intent.getStringExtra("friend")) > 0 ? View.VISIBLE
                            : View.GONE);
            iv_point3
                    .setVisibility(Integer.parseInt(intent.getStringExtra("meitu")) > 0 ? View.VISIBLE
                            : View.GONE);

        }
    }



}
